﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CommerceOne.Common;
using CommerceOne.Domains.Services;
using CommerceOne.Domains.SqlRepositories;
using CommerceOne.Models;
using CommerceOne.Models.Entities;
using CommerceOne.Widgets.Breadcrumb;
using CommerceOne.Widgets.CheckoutStep;

namespace CommerceOne.Controllers
{
    public class AuthenticationController : ControllerBase
    {
        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Registration()
        {
            var viewModel = new RegistrationViewModel();
            InitializeRegistrationViewModel(viewModel);

            viewModel.Contact = new Contact();
            viewModel.Address = new Address();

            return View(viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Registration(RegistrationViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
               
                viewModel.Contact.PasswordSalt = "abcdefgh";
                viewModel.Contact.Addresses = new List<Address> { viewModel.Address };
                viewModel.Address.ModifiedDate = DateTime.Now;
                SqlContactRepository.Instance.Insert(viewModel.Contact);
            } else
            {
                InitializeRegistrationViewModel(viewModel);
            }

            // viewModel.Address.ContactID = viewModel.Contact.ID;
            // SqlAddressRepository.Instance.Add(viewModel.Address);

            return View(viewModel);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Login()
        {
            var parameter = new Parameters { PageType = PageType.Login };

            var viewModel = new LoginViewModel();
            CommonInitialize(viewModel, parameter);

            // Breadcrumb
            var breadcrumbController = new BreadcrumbController { HttpContextBase = this.HttpContext };
            viewModel.Breadcrumb = breadcrumbController.GetViewModel(parameter);
            //  Step
            var checkoutStepController = new CheckoutStepController() { HttpContextBase = this.HttpContext };
            viewModel.Step = checkoutStepController.GetViewModel(parameter.PageType);

            return View(viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(LoginViewModel viewModel)
        {
            var isSubmitForCreatingAccount = Request["SubmitCreate"] != null;

            if (ModelState.IsValid)
            {
                if (isSubmitForCreatingAccount)
                {
                    if (!SqlContactRepository.Instance.IsEmailExisted(viewModel.User))
                    {
                        return RedirectToAction("Registration");
                    }
                    else
                    {
                        viewModel.Errors.Add("Email " + viewModel.User + " 's been already used. Choose another!");
                    }
                }
                else
                {
                    if (AuthenticationService.Instance.ValidateContact(viewModel.User, viewModel.Password))
                    {
                        var contact = SqlContactRepository.Instance.GetByEmail(viewModel.User, true);
                        var userData = contact.ID + "|" + contact.Role.RoleName;
                        var formsAuthenticationTicket = new FormsAuthenticationTicket(1, viewModel.User, DateTime.Now, DateTime.Now.AddMinutes(30), viewModel.RememberMe, userData);
                        var cookiestr = FormsAuthentication.Encrypt(formsAuthenticationTicket);
                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                        if (viewModel.RememberMe) cookie.Expires = formsAuthenticationTicket.Expiration;
                        cookie.Path = FormsAuthentication.FormsCookiePath;
                        Response.Cookies.Add(cookie);

                        return RedirectToAction("MyAccount");
                    }
                    else
                    {
                        viewModel.Errors.Add("You have enter invalid email/password.");
                    }
                }
            }


            var parameter = new Parameters { PageType = PageType.Login };
            CommonInitialize(viewModel, parameter);

            // Breadcrumb
            var breadcrumbController = new BreadcrumbController { HttpContextBase = this.HttpContext };
            viewModel.Breadcrumb = breadcrumbController.GetViewModel(parameter);
            //  Step
            var checkoutStepController = new CheckoutStepController() { HttpContextBase = this.HttpContext };
            viewModel.Step = checkoutStepController.GetViewModel(parameter.PageType);

            return View(viewModel);
        }

        public ActionResult MyAccount()
        {
            var viewModel = new MyAccountViewModel();
            var parameter = new Parameters { PageType = PageType.MyAccount };

            // Breadcrumb
            var breadcrumbController = new BreadcrumbController { HttpContextBase = this.HttpContext };
            viewModel.Breadcrumb = breadcrumbController.GetViewModel(parameter);

            CommonInitialize(viewModel, parameter);
            return View(viewModel);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult PasswordRecover()
        {
            var parameter = new Parameters { PageType = PageType.Login };

            var viewModel = new LoginViewModel();
            CommonInitialize(viewModel, parameter);

            // Breadcrumb
            var breadcrumbController = new BreadcrumbController { HttpContextBase = this.HttpContext };
            viewModel.Breadcrumb = breadcrumbController.GetViewModel(parameter);
            //  Step
            var checkoutStepController = new CheckoutStepController() { HttpContextBase = this.HttpContext };
            viewModel.Step = checkoutStepController.GetViewModel(parameter.PageType);

            return View(viewModel);
        }

        /// <summary>
        /// Initializes the registration view model.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        private void InitializeRegistrationViewModel(RegistrationViewModel viewModel)
        {
            var parameter = new Parameters { PageType = PageType.Login };

            CommonInitialize(viewModel, parameter);

            // Breadcrumb
            var breadcrumbController = new BreadcrumbController { HttpContextBase = this.HttpContext };
            viewModel.Breadcrumb = breadcrumbController.GetViewModel(parameter);
            //  Step
            var checkoutStepController = new CheckoutStepController() { HttpContextBase = this.HttpContext };
            viewModel.Step = checkoutStepController.GetViewModel(parameter.PageType);

            // Country
            viewModel.DefaultCountryId = 199;
            viewModel.Countries = SqlCountryRegionRepository.Instance.GetAllCountryRegion(viewModel.DefaultCountryId);

            // City
            viewModel.Cities = SqlCityRepository.Instance.GetCitiesByCountry(viewModel.DefaultCountryId);
            this.CommonInitialize(viewModel, new Parameters { ObjectId = 0, PageType = PageType.Registration });

            viewModel.SecurityQuestions = SqlRecoverQuestionRepository.Instance.GetActiveSecurityQuestion();

          
        }
    }
}

